package ay.shadow.seckill.controller;

import ay.shadow.seckill.entity.User;
import ay.shadow.seckill.service.IGoodsService;
import ay.shadow.seckill.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.StampedLock;


@RestController
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    private final StampedLock lock = new StampedLock();
    private int data;

    public void updateData() {
        long stamp = lock.readLock(); // 获取读锁
        try {
            int current = data;
            if (needUpdate(current)) {
                // 尝试升级为写锁
                long writeStamp = lock.tryConvertToWriteLock(stamp);
                if (writeStamp != 0) {
                    stamp = writeStamp; // 升级成功
                    data = current + 1;
                } else {
                    // 升级失败，手动释放读锁并获取写锁
                    lock.unlockRead(stamp);
                    stamp = lock.writeLock();
                    data = current + 1;
                }
            }
        } finally {
            lock.unlock(stamp); // 释放锁（可能是读锁或写锁）
        }
    }

    private boolean needUpdate(int value) {
        return value < 10;
    }
    @Autowired
    private IUserService userService;
    @Autowired
    private IGoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    /**
     * @Param
     * @Description 跳转到商品列表页
     * @Return
     */
    // 将页面放到缓存里面，再用redis读取页面渲染到前端，防止超卖
    @RequestMapping(value = "/toList")
    public String toList(Model model, User user, HttpServletRequest request, HttpServletResponse response) {
//        return "goodsList";
                // redis中获取页面，如果不为空，直接返回页面
        ValueOperations operations = redisTemplate.opsForValue();
        String html = (String) operations.get("goodLists");
        if (!StringUtils.isEmpty(html)) {
            return html;
        }
        log.info("{}", user);
        model.addAttribute("user", user);
        model.addAttribute("goodsList", goodsService.findGoodsVo());
        //return "goodsList";
        // 如果为空，手动渲染，并存入redis中
        WebContext context = new WebContext(request, response, request.getServletContext(), response.getLocale(), model.asMap());
        html = thymeleafViewResolver.getTemplateEngine().process("goodsList", context);
        if (!StringUtils.isEmpty(html)) {
            // 设置超时时间
            operations.set("goodsList", html, 60, TimeUnit.SECONDS);
        }
        return html;
    }


//    @RequestMapping(value = "/detail2/{goodsId}", produces = "text/html;charset=utf-8")
//    @ResponseBody
//    public String toDetail2(Model model, User user, @PathVariable Long goodsId, HttpServletRequest request, HttpServletResponse response) {
//        ValueOperations valueOperations = redisTemplate.opsForValue();
//        String html = (String) valueOperations.get("goodsDetail:" + goodsId);
//        // redis中读取页面，如果不为空，直接返回页面
//        if (!StringUtils.isEmpty(html)) {
//            return html;
//        }
//        model.addAttribute("user", user);
//        GoodsVo goodsvo = goodsService.findGoodsVoByGoodsId(goodsId);
//        Date startDate = goodsvo.getStartDate();
//        Date endDate = goodsvo.getEndDate();
//        Date nowDate = new Date();
//        // 秒杀状态
//        int secKillStatus = 0;
//        // 秒杀倒计时
//        int remainSeconds = 0;
//        // 秒杀还未开始
//        if (nowDate.before(startDate)) {
//            remainSeconds = ((int) ((startDate.getTime() - nowDate.getTime()) / 1000));
//        } else if (nowDate.after(endDate)) {
//            // 秒杀已结束
//            secKillStatus = 2;
//            remainSeconds = -1;
//        } else {
//            // 秒杀进行中
//            secKillStatus = 1;
//            remainSeconds = 0;
//        }
//        log.info("{}", secKillStatus);
//        //log.info("{}",vo.toString());
//        model.addAttribute("remainSeconds", remainSeconds);
//        model.addAttribute("secKillStatus", secKillStatus);
//        model.addAttribute("goods", goodsvo);
//
//        WebContext context = new WebContext(request, response, request.getServletContext(), response.getLocale(), model.asMap());
//        html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);
//        if (!StringUtils.isEmpty(html)) {
//            valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
//        }
//        return html;
//        // return "goodsDetail";
//    }
//
//
//
//    @RequestMapping(value = "/detail/{goodsId}")
//    @ResponseBody
//    public RespBean toDetail(Model model, User user, @PathVariable Long goodsId) {
//        //ValueOperations valueOperations = redisTemplate.opsForValue();
//        //String html = (String) valueOperations.get("goodsDetail:" + goodsId);
//        //// redis中读取页面，如果不为空，直接返回页面
//        //if (!StringUtils.isEmpty(html)) {
//        //    return html;
//        //}
//        //model.addAttribute("user", user);
//        GoodsVo goodsvo = goodsService.findGoodsVoByGoodsId(goodsId);
//        Date startDate = goodsvo.getStartDate();
//        Date endDate = goodsvo.getEndDate();
//        Date nowDate = new Date();
//        // 秒杀状态
//        int secKillStatus = 0;
//        // 秒杀倒计时
//        int remainSeconds = 0;
//        // 秒杀还未开始
//        if (nowDate.before(startDate)) {
//            remainSeconds = ((int) ((startDate.getTime() - nowDate.getTime()) / 1000));
//        } else if (nowDate.after(endDate)) {
//            // 秒杀已结束
//            secKillStatus = 2;
//            remainSeconds = -1;
//        } else {
//            // 秒杀进行中
//            secKillStatus = 1;
//            remainSeconds = 0;
//        }
//        DetailVo detailVo = new DetailVo();
//        detailVo.setUser(user);
//        detailVo.setGoodsVo(goodsvo);
//        detailVo.setRemainSeconds(remainSeconds);
//        detailVo.setSecKillStatus(secKillStatus);
//        return RespBean.success(detailVo);
//        //log.info("{}", secKillStatus);
//        //log.info("{}",vo.toString());
//        //model.addAttribute("remainSeconds", remainSeconds);
//        //model.addAttribute("secKillStatus", secKillStatus);
//        //model.addAttribute("goods", goodsvo);
//
//        //WebContext context = new WebContext(request, response, request.getServletContext(), response.getLocale(), model.asMap());
//        //html = thymeleafViewResolver.getTemplateEngine().process("goodsDetail", context);
//        //if (!StringUtils.isEmpty(html)) {
//        //    valueOperations.set("goodsDetail:" + goodsId, html, 60, TimeUnit.SECONDS);
//        //}
//        //return html;
//        // return "goodsDetail";
//
//    }

}
